package Various;

import Jastermind.Game;
import Jastermind.Player;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.XStream;
import java.awt.Color;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.ArrayList;
import javax.swing.JOptionPane;

public class SerialisationXML {
    

    public static void saveToXml(String filename,ArrayList listToSave){
        String entete = "<?xml version='1.0' encoding='ISO-8859-1' ?>\n";
        
        XStream xstream=new XStream(new DomDriver());
        xstream.alias("Color",Color.class);
        xstream.alias("Player",Player.class);
        xstream.alias("Game",Game.class);
        
        try {
                File fichier=new File(filename);
                FileOutputStream fos=new FileOutputStream(fichier);
                fos.write(entete.getBytes());
                xstream.toXML(listToSave,fos);
                fos.close();
        } 
        catch (IOException ex) {
              ex.printStackTrace();
              JOptionPane.showMessageDialog(null,"Une erreur s'est produite pendant l'exportation");
        }
    }
    
    public static ArrayList loadFromXml(String fileName){
        XStream xstream=new XStream(new DomDriver());
        xstream.alias("Color",Color.class);
        xstream.alias("Player",Player.class);
        xstream.alias("Game",Game.class);
        
        ArrayList listToLoad=new ArrayList();
        try {
            FileInputStream fis=new FileInputStream(new File(fileName));
            listToLoad=(ArrayList)xstream.fromXML(fis);
            fis.close();
        } 
        catch (FileNotFoundException ex) {
        }
        catch(IOException ioe){
             ioe.printStackTrace();
             JOptionPane.showMessageDialog(null,"Une erreur s'est produite pendant l'importation");
        }
        return listToLoad;
    }  
}
